<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}">
    <div class="customer-container">
      <div v-loading="infoLoading" :class="{'pb-24':device==='mobile'}" class="customer-info small-padding no-margin mobile-radius">
        <ProgressStep v-if="!showMobilePage" :mode="2" :step-list="stepList" :order-status="stepActiveId" :is-show-correct="false" />
        <el-row v-if="!permissionDenied" :gutter="isShowDrawer ? 0 : 40" style="margin-right: -8px;padding:20px 24px 0;">
          <!-- 详情 -->
          <el-col :span="(detailData.contractInfo && detailData.contractInfo.type === 10) || isShowDrawer? 24 : miniWidth ? 15 : 16">
            <div :class="{'box-scroll pr20':!isShowDrawer}" class="container-scroll-box">
              <explanation :explanation="explanationObj" :countdown="true" @queryProcessData="init" />
              <dynamic-detail
                v-if="detailData.contractInfo && constructions"
                ref="dynamicDetailRef"
                :detail-data="detailData"
                :process-data="processData"
                :operate-data="processData.operation"
                :constructions="constructions"
                :show-mobile-page="showMobilePage"
                :stamp-required="stampRequired"
                :is-current-version="isCurrentVersion"
                :is-part-time-worker="isPartTimeWorker"
                :attachment-card-id="attachmentCardId"
                @changeRadioValue="changeRadioValue"
                @refreshAttachment="refreshAttachment" />
              <LinkedAccount
                v-if="detailData.contractInfo && (detailData.contractInfo.type === CONTRACT_TYPE.KOL)"
                v-model="detailData.accountList"
                :can-sync-account="processData.processStatus === 4"
                :sync-disabled="syncDisabled"
                @handleSyncAccount="handleSyncAccount"
              />
              <relatedOrderList
                v-if="detailData.contractInfo && (detailData.contractInfo.type === 2 || detailData.contractInfo.type === 3)"
                :operate-data="processData.operation"
                :detail-data="detailData.orders"
                :show-mobile-page="showMobilePage"
                :total-amount="orderTotalAmount" />
              <staffRelatedOrderList v-if="!isPartTimeWorker && detailData.contractInfo && (detailData.contractInfo.type === 1)" :total-amount="orderTotalAmount" :detail-data="detailData.orders" :show-mobile-page="showMobilePage"/>
              <div v-if="!isPartTimeWorker && detailData.contractInfo && detailData.contractInfo.type !== 10">
                <RelatedContractTable :list="detailData.contractList || []" style="margin-top: 24px; margin-bottom: 20px" />
                <template v-if="isShowRelatedOrder">
                  <table-title
                    :total="realOrders.length"
                    :tips="realOrdersTips"
                    :style="`margin-bottom: 16px;margin-top: 32px; ${showMobilePage && (isCreate || isApply) ? 'padding-bottom: 40px' : ''}`"
                    title="实际关联订单"
                    is-show
                  >
                    <el-button
                      v-if="(isCreate || isApply) && isCurrentVersion"
                      :style="`${showMobilePage?'left: 0; top: 16px':''}`"
                      type="primary"
                      plain
                      size="small"
                      class="empty-btn-style title-btn-right"
                      @click="relatedOrdersShow"
                    >关联订单</el-button>
                  </table-title>
                  <dynamic-edit-table
                    ref="dynamicEditTableRef"
                    :list-data="realOrders"
                    :list-setting="realLegalOrderSetting"
                    :show-add-btn="false"
                    :show-mobile-page="showMobilePage"
                    :is-edit="false"
                    show-serial
                    style="margin-left: 4px"
                  />
                </template>
              </div>
            </div>
          </el-col>
          <!-- 流程 -->
          <el-col v-if="(detailData.contractInfo && detailData.contractInfo.type !== 10) && !isShowDrawer" :span="miniWidth ? 9 : 8" class="process-box">
            <div class="progress-type-box">
              <div :class="progressType === 0 ? 'active' : ''" class="progress-type-btn" @click="progressType = 0">审批日志</div>
              <div :class="progressType === 1 ? 'active' : ''" class="progress-type-btn" @click="progressType = 1">审批进度</div>
              <div v-if="hasRouteAuth('crm:contract:record:read')" :class="progressType === 2 ? 'active' : ''" class="progress-type-btn" @click="progressType = 2">修改记录</div>
              <div :class="progressType === 3 ? 'active' : ''" class="progress-type-btn" @click="progressType = 3">附件记录</div>
            </div>
            <div :class="{ 'pd-top0': progressType === 3 }" class="process-content-box scroll-box">
              <auditProcess
                v-loading="listLoading"
                v-if="progressType === 0"
                :list="processCollectionList"
                :process-status="processData.processStatus"
                :comment-status="commentStatus"
                :all-approver="allApprover"
                :is-creator="isCreate"
                :approval-module-type="APPROVAL_MODULE_TYPE.CONTRACT"
                :is-drawer="false"
                @onCommentStatusChange="onCommentStatusChange"
                @showCommentDialog="showCommentDialog"
                @onReplyComment="onReplyComment"
                @reloadComment="getProcessList" />
              <AuditProgressWrap
                v-else-if="progressType === 1"
                :default-aduitor-list="proposer"
                :flow-structure="auditScheduleData"
                :operate-data="processData.operation"
                :process-data="auditScheduleData"
                :has-press-auth="hasPressAuth"
                :process-status="processData.processStatus"
                :senders="senders"
                @addSigner="addSigner"
                @pressSendMsg="pressSendMsg" />
              <recordList v-else-if="progressType === 2" :id="processId" :type="0" @freshDetail="getData" @getHistoryDetail="getHistoryDetail($event,0)" @setCurrentVersion="setCurrentVersion"/>
              <AttachmentList v-else-if="progressType === 3" ref="attachmentListRef" :contract-id="contractId" />
              <empty-placeholder v-else style="height: 400px;" />
            </div>
          </el-col>
          <div v-if="(detailData.contractInfo && detailData.contractInfo.type !== 10) && isShowDrawer" class="suspend-btn" @click="isShowProcess = true">
            <i class="el-icon-arrow-left icon"/>
            <div class="text">
              <div style="margin-bottom: 3px;">审批</div>
              <div>流程</div>
            </div>
          </div>
          <!-- 流程弹窗 -->
          <el-drawer
            v-if="(detailData.contractInfo && detailData.contractInfo.type !== 10) && isShowDrawer"
            :visible.sync="isShowProcess"
            :with-header="false"
            :size="'34%'"
            custom-class="process-drawer process-drawer-bg">
            <div :class="{'progress-type-in-mobile': showMobilePage}" class="progress-type-box" style="margin-top:12px">
              <div :class="progressType === 0 ? 'active' : ''" class="progress-type-btn" @click="progressType = 0">审批日志</div>
              <div :class="progressType === 1 ? 'active' : ''" class="progress-type-btn" @click="progressType = 1">审批进度</div>
              <div v-if="hasRouteAuth('crm:contract:record:read')" :class="progressType === 2 ? 'active' : ''" class="progress-type-btn" @click="progressType = 2">修改记录</div>
              <div :class="progressType === 3 ? 'active' : ''" class="progress-type-btn" @click="progressType = 3">附件记录</div>
            </div>
            <div :class="{'process-content-box':progressType !== 2, 'pd-top0': progressType === 3}">
              <auditProcess
                v-loading="listLoading"
                v-if="progressType === 0"
                :list="processCollectionList"
                :process-status="processData.processStatus"
                :comment-status="commentStatus"
                :all-approver="allApprover"
                :is-creator="isCreate"
                :approval-module-type="APPROVAL_MODULE_TYPE.CONTRACT"
                @onCommentStatusChange="onCommentStatusChange"
                @showCommentDialog="showCommentDialog"
                @onReplyComment="onReplyComment"
                @reloadComment="getProcessList" />
              <AuditProgressWrap
                v-else-if="progressType === 1"
                :default-aduitor-list="proposer"
                :flow-structure="auditScheduleData"
                :operate-data="processData.operation"
                :process-data="auditScheduleData"
                :has-press-auth="hasPressAuth"
                :process-status="processData.processStatus"
                :senders="senders"
                @addSigner="addSigner"
                @pressSendMsg="pressSendMsg" />
              <recordList v-else-if="progressType === 2" :id="processId" :type="0" @freshDetail="getData" @getHistoryDetail="getHistoryDetail($event,0)" @setCurrentVersion="setCurrentVersion"/>
              <AttachmentList v-else-if="progressType === 3" ref="attachmentListRef" :contract-id="contractId" />
              <empty-placeholder v-else style="height: 400px;" />
            </div>
          </el-drawer>
        </el-row>
        <DeniedPlaceholder v-else />
      </div>
      <processOperation
        v-if="detailData.contractInfo && detailData.contractInfo.type !== 10"
        ref="processOperation"
        :disabled="listLoading"
        :operate-data="processData.operation"
        :comment-total="commentCount"
        :process-status="processData.processStatus"
        :is-create="isCreate"
        :flow-structure="auditScheduleData"
        :is-apply="isApply"
        :show-comment-btn="true"
        :process-data-list="processData.list"
        :is-current-version="isCurrentVersion"
        :permission-denied="permissionDenied"
        :is-show-stamp-fixed-tip="isShowStampFixedTip"
        @handlePressSend="handlePressSend"
        @handleRevocation="handleRevocation"
        @handleRecall="handleRecall"
        @handleAudit="handleAudit"
        @handleReapply="handleReapply"
        @handleCreateNew="handleCreateNew('EditContract',{id: encryption(contractId)},{reapply: processId})"
        @handleSendMsg="handleSendMsg"
        @handleRemodify="handleRemodify"
        @handleAddSigner="handleAddSigner"
        @deliverTo="deliverTo"
        @toBack="toBack"
        @showCommentDialog="showCommentDialog"
        @handleHigherRecall="handleHigherRecall"
        @handleResubmit="handleResubmit"
        @handleApproverChange="handleApproverChange"
        @handleModify="handleModify('EditContract',{id: encryption(contractId)},{remodify: processId})"
        @handleCancelPress="handleCancelPress"
        @handleToggleProcess="handleToggleProcess"
        @handleComment="showCommentDialog"
        @handleCloseProcess="handleCloseProcess"
      >
        <el-button v-if="showSupplierAuditBtn" type="primary" size="small" style="height: 32px;margin-left: 0;" @click="toSupplierAudit">发起付款申请</el-button>
      </processOperation>
      <processOperation
        v-else
        :type="3"
        :comment-total="commentCount"
        :permission-denied="permissionDenied"
        @toBack="toHisBack"
        @handleHisEdit="handleHisEdit"
        @showCommentDialog="showCommentDialog"
        @handleCloseProcess="handleCloseProcess"
      />
      <ding-ding-dialog
        ref="pressSendDialogRef"
        :btn1="'确认加急'"
        :btn2="'取消'"
        :show-send-checkbox="false"
        :select-with-user-load="false"
        :default-list="pressDefaultList"
        redirect-url="/legal/contractDetail"
        summary-title="加急原因"
        title="催办通知"
        @handelOK="toSend" />
      <!-- v2.9.7 新增传参数 defaultAduitorList,operateData-->
      <auditDialog
        ref="auditDialog"
        :loading="auditLoading"
        :type="type"
        :operate-data="processData.operation"
        :default-aduitor-list="proposer"
        :create-user="createUser"
        :dialog-form-visible="dialogFormVisible"
        :content="processData.operation.content"
        :audit-schedule-data="auditScheduleData"
        @close="closeDialog"
        @handleSubmit="handleSubmit"/>
      <divers-auditor-dialog ref="auditorDialog" :can-empty="false" @userSelect="sumbmitDeliverTo" @handleSender="handleSender"/>
      <CommentDialog
        ref="commentDialogRef"
        :comments-id="contractId"
        :comment-module="COMMENT_MODULE.CONTRACT"
        :add-comment-api="legalCommentAdd"
        @sendCallback="sendCallback"
      />
      <related-orders
        ref="relatedOrders"
        :visible.sync="showRelatedOrders"
        @confirmRelatedOrder="confirmRelatedOrder"
        @onBack="relatedDrawerHide"
      />
      <ApproverChange
        ref="approverChangeDialog"
        :business-type="BUSINESS_TYPE.CONTRACT"
        :ids="contractId"
        @changeCallBack="init"
      />
      <el-image v-if="auditScheduleData.isExpedited && auditScheduleData.isExpedited === 1" :src="pressImg" class="press-img"/>
      <el-image v-if="auditScheduleData.isExpedited && auditScheduleData.isExpedited === 2" :src="pressCancelImg" class="press-img"/>
    </div>
  </div>
</template>

<script>
// 动态 详情信息
import { weMediaLegalDetailConstruct, staffLegalDetailConstruct, ipAccreditDetailConstruct, kolDetailConstruct,
  platformDetailConstruct, eCommerceDeatailConstruct, investDetailConstruct, otherDetailConstruct,
  historyDetailConstruct } from './model/detailConstruction';
import DynamicDetail from './module/dynamicDetail';
// 结束
import RelatedContractTable from '@/components/SupplierComponent/relatedContractTable/relatedContractTable';
import DiversAuditorDialog from '@/components/Common/auditProcess/module/diversAuditorDialog';
import AuditProgressWrap from '@/components/Common/auditProcess/auditProgress';
import ApproverChange from '@/components/Common/auditProcess/approverChange';
import AttachmentList from '@/components/Common/auditProcess/attachmentList';
import processOperation from '@/components/AuditProcess/processOperation';
import dynamicEditTable from '@/components/Common/dynamicEditTable';
import ProgressStep from '@/components/CreateOrder/orderDetail/step';
import RecordList from '@/components/Common/auditProcess/recordList';
import auditDialog from '@/components/AuditProcess/auditDialog';
import CommentDialog from '@/components/Common/commentDialog';
import relatedOrders from '@/components/legal/relatedOrders';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import auditProcess from '@/components/AuditProcess/index';
import explanation from '@/components/Common/explanation';
import tableTitle from '@/components/Title';
import staffRelatedOrderList from './module/staffRelateOrderList';
import relatedOrderList from './module/relatedOrderList';
import detailInfoBase from './module/detailInfoBase';
import LinkedAccount from '@/components/legal/linkedAccount';
import { realLegalOrderSetting } from '../module/orderSetting';
import { getContractDetail, getProcessList, postProcessAudit, postRevocation, postRecall, scheduleCounterSign,
  sumbDeliverTo, pressSendMsg, contractHigherRecall, contractResubmit, storeRealOrders, legalCommentAdd,
  getApproveLatestInfo, getComments, editStampType, contractAccountSync, getContractAttachmentList
} from '@/api/legal';
import { BUSINESS_TYPE, COMMENT_STATUS, PROCESS_TYPE } from '@/utils/const/process';
import { COMMENT_MODULE, APPROVAL_MODULE_TYPE } from '@/utils/const';
import { CONTRACT_TYPE } from '@/utils/const/contract';
import { hasRouteAuth } from '@/utils/permission';
import { decrypt, encryption } from '@/utils';
import { showModal } from '@/utils/message';
import { getCurrentZeroTime } from '@/utils';
import { standardFormat } from '@/filters/date';
import OperationRelatedOrders from '../create/mixins/operationRelatedOrders';
import filterObjStoreMixin from '@/mixins/filterObjStore';
import setProcessLog from '@/mixins/setProcessLog';
import commentDel from '@/mixins/commentDel';
import schedule from '@/mixins/schedule';
import pressCancelImg from '@/assets/press_cancel.png';
import pressImg from '@/assets/press_top.png';
import { MessageBox } from 'element-ui';
import { mapState } from 'vuex';

export default {
  components: {
    auditDialog,
    auditProcess,
    processOperation,
    tableTitle,
    detailInfoBase,
    EmptyPlaceholder,
    relatedOrderList,
    DynamicDetail,
    staffRelatedOrderList,
    dynamicEditTable,
    AuditProgressWrap,
    DiversAuditorDialog,
    CommentDialog,
    relatedOrders,
    ApproverChange,
    explanation,
    RelatedContractTable,
    RecordList,
    AttachmentList,
    LinkedAccount,
    ProgressStep
  },
  filters: {
    standardFormat
  },
  mixins: [OperationRelatedOrders, schedule, commentDel, filterObjStoreMixin, setProcessLog],
  data() {
    return {
      CONTRACT_TYPE,
      encryption,
      legalCommentAdd,
      COMMENT_MODULE,
      BUSINESS_TYPE,
      APPROVAL_MODULE_TYPE,
      // weMediaLegalDetailConstruct, // 渠道 和 推广销售类
      // staffLegalDetailConstruct, // 一般购销/委托服务类
      // ipAccreditDetailConstruct, // ip类
      // kolDetailConstruct, // kol 类
      // platformDetailConstruct, // 平台
      // eCommerceDeatailConstruct, // 电商
      // investDetailConstruct, // 投资
      // otherDetailConstruct, // 其他
      // historyDetailConstruct,
      realLegalOrderSetting,
      detailData: {},
      infoLoading: false,
      processData: {
        list: [],
        operation: {
          auth: [],
          content: null
        }
      },
      contractId: '',
      deliverToType: null, // 转交类型 暂存
      contractRelatedData: null,
      type: null, // 0：拒绝 1：同意
      progressType: 0,
      listLoading: false,
      dialogFormVisible: false,
      auditLoading: false,
      miniWidth: false,
      commentStatus: COMMENT_STATUS.SHOW_ALL,
      showNewComment: false,
      showRelatedOrders: false,
      commentCount: 0,
      realOrders: [], // 实际关联订单列表
      commentList: [],
      processCollectionList: [], // 评论和日志排序后的合集
      pressImg,
      pressCancelImg,
      legalFinId: null,
      currentNodeId: null,
      orderTotalAmount: 0, // 订单总含税金额
      isShowProcess: false,
      stampRequired: false,
      syncDisabled: false,
      isShowRelatedOrder: false,
      permissionDenied: false, // 无详情查看权限
      isShowStampFixedTip: false, // 盖章事件提示没在可视窗口时在底部显示出来
      isPartTimeWorker: false, // 购销合同选中兼职人员合作
      attachmentCardId: 0 // 附件记录第一个卡片Id
    };
  },
  computed: {
    proposer() {
      if (!this.detailData || !this.detailData.createInfo || !this.detailData.createInfo.proposer) {
        return [];
      }
      const { userName, proposerAvatar, id, deptName } = this.detailData.createInfo.proposer;
      let post = '';
      if (deptName && deptName.length > 0) {
        post = deptName[0].name;
      }
      const data = [{
        userName,
        avatar: proposerAvatar,
        id,
        post
      }];
      return data;
    },
    ...mapState({
      'device': state => state.app.device,
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    // 是创建者或管理员
    hasPressAuth() {
      return this.isAdmin || (this.detailData.createInfo && this.userInfo.id === this.detailData.createInfo.creator.id);
    },
    constructions() {
      const type = this.detailData.contractInfo ? this.detailData.contractInfo.type : 0;
      let constructions;
      switch (type) {
        case 1: constructions = staffLegalDetailConstruct; break;
        case 2:
        case 3: constructions = weMediaLegalDetailConstruct; break;
        case 4: constructions = ipAccreditDetailConstruct; break;
        case 5: constructions = kolDetailConstruct; break;
        case 6: constructions = platformDetailConstruct; break;
        case 7: constructions = eCommerceDeatailConstruct; break;
        case 8: constructions = investDetailConstruct; break;
        case 9: constructions = otherDetailConstruct; break;
        case 10: constructions = historyDetailConstruct; break;
        default:
          break;
      }
      return constructions;
    },
    isCreate() { // 创建人
      const creator = this.detailData && this.detailData.createInfo && this.detailData.createInfo.creator ? this.detailData.createInfo.creator : {};
      return this.userInfo.id === creator.id;
    },
    createUser() {
      const creator = this.detailData && this.detailData.createInfo ? this.detailData.createInfo.creator : {};
      let user = creator;
      if (this.isCreate) {
        user = this.userInfo;
      }
      return user;
    },
    isApply() { // 申请人
      const proposer = this.detailData && this.detailData.createInfo ? this.detailData.createInfo.proposer : {};
      return proposer && this.userInfo.id === proposer.id;
    },
    realOrdersTips() {
      return '注意：该列表仅用作展示订单与合同的关联关系，与审批内容无关';
    },
    getContinueApproveStatus() {
      const continueApproveLocalKey = 'CONTINUE_APPROVE_' + this.userInfo.id;
      const getApproveLocalStatus = window.localStorage.getItem(continueApproveLocalKey);
      return ![null, 'false'].includes(getApproveLocalStatus);
    },
    isShowDrawer() { // 是否显示流程弹窗
      return this.showMobilePage || this.miniWidth;
    },
    stepList() {
      return [
        { name: '选择类型', id: 0 },
        { name: '填写信息', id: 1 },
        { name: '合同审批', id: 2 },
        { name: '流程结束', id: 3 }
      ];
    },
    stepActiveId() {
      return [3, 4].includes(this.processData.processStatus) ? 3 : 2;
    },
    showSupplierAuditBtn() {
      const types = [CONTRACT_TYPE.STAFF, CONTRACT_TYPE.SPREAD, CONTRACT_TYPE.PURCHASE];
      const oppCompanyTypes = [0, 2];// 飞博供应商、萌力供应商
      const { type, oppCompanyType } = this.detailData.contractInfo || {};
      return types.includes(type) && (this.processData.processStatus === 4 || (this.legalFinId && this.legalFinId < this.currentNodeId)) && oppCompanyTypes.includes(oppCompanyType) && hasRouteAuth('medium:supplierAudit:launch');
    }
  },
  watch: {
    '$route'(to, from) {
      if (to.params.id !== from.params.id || to.query.processId !== from.query.processId) {
        this.contractId = Number(decrypt(to.params.id));
        this.processId = Number(decrypt(to.query.processId));
        this.init();
      }
    }
  },
  created() {
    this.contractId = Number(decrypt(this.$route.params.id));
    this.processId = Number(decrypt(this.$route.query.processId));
    this.init();
    window.addEventListener('resize', this.isMini);
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.isMini);
    window.removeEventListener('scroll', this.handleScroll, true);
  },
  methods: {
    hasRouteAuth,
    isMini() {
      this.miniWidth = window.innerWidth < 1400;
      this.handleScroll();
    },
    // 获取法务定稿节点id
    findLegalFinId(process) {
      const temp = process.filter(it => it.nodeName === '审批');
      temp.forEach(it => {
        if (it.examineRoles[0].roleName === '法务定稿') {
          this.legalFinId = it.id;
        }
      });
    },
    getAttachmentList() {
      getContractAttachmentList(this.contractId).then(res => {
        if (res.code === 200 && res.data.length) {
          this.attachmentCardId = res.data[0].id;
        }
      }).catch(_ => {});
    },
    refreshAttachment() {
      if (this.$refs.attachmentListRef) this.$refs.attachmentListRef.getContractAttachmentList(this.contractId);
    },
    init() {
      this.getData().then(res => {
        if (res.contractInfo.type !== 10) {
          this.queryProcessData();
        }
      });
      this.isMini();
      this.getAttachmentList();
      // 只有从合同管理跳转才展示实际关联订单
      const newQuery = JSON.parse(JSON.stringify(this.$route.query));
      if (newQuery.isFromManageIndex && !this.$route.query.fromList) {
        delete newQuery.isFromManageIndex;
        this.$route.params.isFromManageIndex = 1;
        this.$router.replace({ query: newQuery, params: this.$route.params });
      }
      if (this.$route.params.isFromManageIndex) {
        this.isShowRelatedOrder = true;
      }
    },
    handleScroll: _.throttle(function() {
      if (this.processData.operation.setEvents && this.processData.operation.setEvents.includes(12) && ![0, 1].includes(this.detailData.contractInfo.stampType)) {
        this.$nextTick(() => {
          const stamTip = document.querySelector('.stamp-tip');
          const pagination = document.querySelector('.pagination-flex');
          const y = pagination.offsetTop;
          if (stamTip && stamTip.getBoundingClientRect()) {
            const top = stamTip.getBoundingClientRect().top;
            this.isShowStampFixedTip = !!(top > y);
          }
        });
      } else {
        this.isShowStampFixedTip = false;
      }
    }, 500),
    queryProcessData() {
      this.getProcessList();
      this.getAuditSchedule();
    },
    getData() {
      this.infoLoading = true;
      return new Promise((resolve, reject) => {
        getContractDetail(this.contractId).then(res => {
          if (res.data.processId && this.processId) this.handleProcessCheck(res.data.processId);
          this.handleDetailData(res);
          if (res.code === 200) { resolve(res.data); }
        }).catch(err => {
          if (err.code === 403) {
            this.permissionDenied = true;
          }
          this.infoLoading = false;
          reject(err);
        });
      });
    },
    handleDeadline() {
      // 合同有效期过期置灰同步资源按钮
      if (this.detailData.contractInfo && this.detailData.contractInfo.deadline && this.detailData.contractInfo.deadline.length && Number(this.detailData.contractInfo.deadline[1]) < getCurrentZeroTime()) {
        this.syncDisabled = true;
      }
    },
    // 处理详情接口返回的数据
    handleDetailData(res) {
      this.infoLoading = false;
      if (res.code === 200) {
        if (res.data.contractList && res.data.contractList.length) {
          res.data.contractList.map(it => {
            it.userName = it.proposerName;
            if (it.contractSourceType === 1) it.disable = true;
            return it;
          });
        }
        this.detailData = res.data;
        this.handleDeadline();
        this.initCountdown(res.data);
        this.realOrders = this.formatRealOrders(res.data);
        this.commentCount = res.data.commentCount;
        this.isPartTimeWorker = this.setPartTimeWorkerType();
        this.currentNodeId = res.data.aduitInfo.currentNode;
        this.findLegalFinId(res.data.aduitInfo.process);
        let orderTotalAmount = 0;
        if (Array.isArray(res.data.orders)) {
          res.data.orders.forEach(el => {
            if (el.contractPrice) {
              orderTotalAmount += Number(el.contractPrice);
            }
          });
          this.orderTotalAmount = orderTotalAmount.toFixed(2);
        }
        !this.detailData.accountList && this.$set(this.detailData, 'accountList', []);
      }
    },
    setPartTimeWorkerType() {
      if (this.detailData.contractInfo && this.detailData.contractInfo.type === CONTRACT_TYPE.STAFF) {
        const { type } = this.detailData.contractInfo.cooperDate;
        return type === 4;
      }
    },
    changeRadioValue(stampType) {
      this.stampRequired = false;
      const params = {
        stampType,
        id: this.contractId
      };
      editStampType(params).then(res => {
        if (res.code === 200) {
          this.$message.success('操作成功');
          this.init();
        }
      }).catch(err => console.error(err.message));
    },
    onCommentStatusChange(status) {
      this.commentStatus = status;
      this.getProcessList();
    },
    onReplyComment(commentData) {
      this.$refs['commentDialogRef'].dialogVisible = true;
      this.$refs['commentDialogRef'].handleReply(commentData);
    },
    initCountdown(data) {
      // 优化 process 也是数组
      // const examineRoles = data && data.aduitInfo && data.aduitInfo.process && data.aduitInfo.process.examineRoles || [];
      // const lastRole = examineRoles.length && examineRoles[examineRoles.length - 1] || {};
      // if (lastRole.status === 3) { // 审批中
      // lastRole.isTimeout
      // }
    },
    formatRealOrders(data) {
      if (!data || !Array.isArray(data.realOrders) || !data.realOrders.length) {
        return [];
      }
      const orderTypeData = {
        1: '渠道订单',
        2: '项目订单',
        4: '项目渠道单'
      };
      data.realOrders.forEach(item => {
        item.orderTypeName = orderTypeData[item.orderType];
      });
      return data.realOrders;
    },
    sendCallback() {
      this.getProcessList();
      if (this.$refs.attachmentListRef) this.$refs.attachmentListRef.getContractAttachmentList(this.contractId);
    },
    async getProcessList() {
      try {
        this.listLoading = true;
        this.commentList = [];
        if (this.commentStatus !== COMMENT_STATUS.SHOW_COMMENT) {
          const processParams = { id: this.processId };
          const processResult = await getProcessList(processParams);
          this.processData = processResult.data;
          this.handleScroll();
        }
        if (this.commentStatus !== COMMENT_STATUS.HIDE_COMMENT) {
          const commentParams = Object.create(null);
          commentParams.id = this.contractId;
          commentParams.page = 1;
          commentParams.perPage = 0;
          const commentResult = await getComments(commentParams);
          this.commentList = commentResult.data;
          this.commentCount = commentResult.count;
        }
        const processList = this.commentStatus !== COMMENT_STATUS.SHOW_COMMENT ? _.cloneDeep(this.processData.list) : [];
        this.$nextTick(() => {
          this.processCollectionList = this.setProcessList(processList);
        });
        this.listLoading = false;
      } catch (error) {
        this.listLoading = false;
      }
    },
    getAuditSchedule() {
      this.requestAuditSchedule(this.processId);
    },
    closeDialog() {
      this.dialogFormVisible = false;
    },
    // 审批
    handleSubmit(type, data) {
      const params = Object.assign({
        id: this.processId,
        status: type,
        examineRoleId: this.processData.operation.examineRoleId
      }, data);
      this.auditLoading = true;
      postProcessAudit(params).then(res => {
        if (res.code === 200) {
          this.handleScroll();
          this.$message({ type: 'success', message: '提交成功' });
          this.closeDialog();
          this.getContinueApproveStatus ? this.continueNextApprove() : this.init();
          if (this.$refs.attachmentListRef) this.$refs.attachmentListRef.getContractAttachmentList(this.contractId);
        } else {
          this.$message.closeAll();
          this.$message({ type: 'error', message: res.message });
        }
        this.auditLoading = false;
      }).catch(err => {
        if (err.message === '盖章类型不能为空！') {
          this.stampRequired = true;
        }
        console.log(err);
        this.auditLoading = false;
        this.$message.closeAll();
        this.$message({ type: 'error', message: err.message });
      });
    },
    // 继续下一个审批
    continueNextApprove() {
      const params = Object.create(null);
      params.businessType = BUSINESS_TYPE.CONTRACT;
      params.processId = this.processId;
      params.filterData = this.getFilterObj(PROCESS_TYPE.CONTRACT);
      getApproveLatestInfo(params).then(res => {
        if (res.data.finished) {
          this.init();
          this.getContinueApproveStatus && this.$nextTick(() => {
            const message = this.getFinishedMessage(PROCESS_TYPE.CONTRACT);
            this.$message.closeAll();
            this.$message.success(message);
          });
        } else {
          this.goNextApproveDetail(res.data);
        }
      });
    },
    // 跳转合同详情页
    goNextApproveDetail(data) {
      const RN = Math.floor(Math.random() * 10000);
      const { fromTodo, fromList } = this.$route.query;
      this.$router.push({
        name: 'contractDetail',
        params: {
          id: this.encryption(data.id)
        },
        query: {
          RN,
          processId: this.encryption(data.processId),
          fromTodo,
          fromList
        }
      });
    },
    sumbmitDeliverTo(data) {
      const type = this.deliverToType;
      if (!data.selectUser || data.selectUser.length === 0) {
        this.$message({ type: 'warning', message: '请选择转交人' });
        return;
      }
      let params;
      if (type === 1) {
        params = {
          id: this.processId,
          type,
          deliver: data.selectUser[0].id
        };
      } else {
        params = {
          id: this.processId,
          type,
          deliver: data.selectUser[0].id,
          examineRoleId: this.processData.operation.examineRoleId
        };
      }
      sumbDeliverTo(params).then(res => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '转交成功'
          });
          this.getAuditSchedule();
          this.getProcessList();
          if (type === 1) {
            this.getData();
          }
        }
      });
      this.deliverToType = null;
    },
    // 转交
    deliverTo(type) { // type: 1: 申请人转交；2：审批转交
      this.$refs.auditorDialog.dialogVisible = true;
      this.deliverToType = type;
      let title = '';
      switch (type) {
        case 1:
          title = '申请人转交';
          break;
        case 2:
          title = '转交';
          break;
      }
      this.$refs.auditorDialog.initDeliverTo(1, title);
    },
    // 撤回
    handleRecall(auth) {
      const h = this.$createElement;
      const recallAll = () => {
        MessageBox.close();
        this.handleRecallAll(false);
      };
      const recallPrev = () => {
        MessageBox.close();
        this.handleRecallPrev(false);
      };
      if (auth.includes(5) && auth.includes(3)) {
        MessageBox.confirm('', '', {
          message: h('p', null, [
            h('div', null, '请确认撤回至哪个步骤'),
            h('div', { class: 'btns-container' }, [
              h('el-button', { on: { click: recallAll }, class: '', props: { type: 'primary' }}, '撤回至任务发起'),
              h('el-button', { on: { click: recallPrev }, class: '' }, '撤回至上一步'),
              h('el-button', { on: { click: MessageBox.close }, class: 'cancel-btn' }, '返回')
            ])
          ]),
          confirmButtonText: '',
          cancelButtonText: '',
          showClose: false,
          showCancelButton: false,
          showConfirmButton: false,
          type: 'warning',
          lockScroll: false,
          customClass: 'del-message del-message-cancel message-box-order',
          iconClass: 'del-icon',
          center: true
        });
      } else if (auth.includes(3)) {
        this.handleRecallPrev();
      } else {
        this.handleRecallAll();
      }
    },
    // 选择完加签人的逻辑
    addSigner(data) {
      const param = {
        id: this.processId,
        examineRoles: [data]
      };
      scheduleCounterSign(param).then(res => {
        if (res.code === 200) {
          this.getAuditSchedule();
          this.getProcessList();
        }
      });
    },
    // 点击加签按钮逻辑
    handleAddSigner() {
      this.progressType = 1;
      if (this.showMobilePage) {
        this.isShowProcess = true;
      }
    },
    handlePostRecall(params) {
      postRecall(params).then(res => {
        if (res.code === 200) {
          this.$message({ type: 'success', message: '撤回成功' });
          this.init();
        } else {
          this.$message.closeAll();
          this.$message({ type: 'error', message: res.message });
        }
      }).catch(err => {
        console.log(err);
        this.$message.closeAll();
        this.$message({ type: 'error', message: err.message });
      });
    },
    handleRecallPrev(confirm = true) {
      const params = {
        id: this.processId,
        type: 0
      };
      if (confirm) {
        showModal('请确认是否撤回', '', {
          cancelButtonText: '返回',
          lockScroll: false,
          iconClass: 'del-icon'
        }).then(() => {
          this.handlePostRecall(params);
        });
      } else {
        this.handlePostRecall(params);
      }
    },
    // 撤回至发起
    handleRecallAll(confirm = true) {
      const params = {
        id: this.processId,
        type: 1
      };
      if (confirm) {
        showModal('请确认是否撤回', '', {
          confirmButtonText: '撤回至任务发起',
          cancelButtonText: '返回',
          customClass: 'del-message del-message-cancel message-btn-margin',
          lockScroll: false,
          iconClass: 'del-icon'
        }).then(() => {
          this.handlePostRecall(params);
        });
      } else {
        this.handlePostRecall(params);
      }
    },
    handleCloseProcess(params) {
      showModal('请确认是否结束流程', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'del-message del-message-cancel inloive-abandon-message-btn-margin',
        lockScroll: false,
        iconClass: 'del-icon'
      }).then(() => {
        this.handleRevocation();
      });
    },
    // 撤销
    handleRevocation() {
      const params = {
        id: this.processId
      };
      postRevocation(params).then(res => {
        if (res.code === 200) {
          this.$message({ type: 'success', message: '作废成功' });
          this.init();
        } else {
          this.$message.closeAll();
          this.$message({ type: 'error', message: res.message });
        }
      }).catch(err => {
        console.log(err);
        this.$message.closeAll();
        this.$message({ type: 'error', message: err.message });
      });
    },
    // 修改
    handleRemodify(params) {
      this.$router.push({
        name: 'EditContract',
        params: {
          id: this.encryption(this.contractId)
        },
        query: {
          remodify: this.processId
        }
      });
    },
    // 重新申请
    handleReapply(params) {
      const h = this.$createElement;
      const toEdite = () => {
        this.$router.push({
          name: 'EditContract',
          params: {
            id: this.encryption(this.contractId)
          },
          query: {
            reapply: this.processId
          }
        });
        MessageBox.close();
      };
      const toDetail = () => {
        const routeUrl = this.$router.resolve({
          name: 'contractDetail',
          params: {
            id: params.relatedId
          },
          query: {
            processId: params.relatedProcessId
          }
        });
        MessageBox.close();
        window.open(routeUrl.href, '_blank');
      };
      if (params.relatedProcessId && params.relatedId) {
        MessageBox.confirm('', '', {
          message: h('p', null, [
            h('div', null, '已有重新申请的合同，是否继续新建'),
            h('div', { class: 'btns-container' }, [
              h('el-button', { on: { click: toEdite }, class: 'resolve-btn', props: { type: 'primary' }}, '新建'),
              h('el-button', { on: { click: toDetail }, class: 'reject-btn' }, '查看'),
              h('el-button', { on: { click: MessageBox.close }, class: 'cancel-btn' }, '再想想')
            ])
          ]),
          confirmButtonText: '新建',
          cancelButtonText: '再想想',
          showClose: false,
          showCancelButton: false,
          showConfirmButton: false,
          type: 'warning',
          lockScroll: false,
          customClass: 'del-message del-message-cancel message-box-order',
          iconClass: 'del-icon',
          center: true
        });
      } else {
        // 首次重新申请
        toEdite();
      }
    },
    handleAudit(value) {
      this.type = value;
      this.dialogFormVisible = true;
    },
    toBack() {
      if (this.$route.query.fromTodo) {
        this.$router.go(-1);
      } else {
        this.$router.push({
          name: 'ContractManagement'
        });
      }
    },
    toHisBack() {
      // 如果没有详情查看权限默认跳转至合同审批列表页
      let routeName = 'ContractManagementHistory';
      if (this.permissionDenied) {
        if (hasRouteAuth('crm:contract:read')) {
          routeName = 'ContractManagement';
        } else if (!hasRouteAuth('crm:contractManage:read')) {
          routeName = 'Index';
        }
      }
      this.$router.push({
        name: routeName
      });
    },
    handleHisEdit() {
      this.$router.push({
        name: 'hisEditContract',
        params: {
          id: this.contractId
        }
      });
    },
    // 催办通知回调
    async pressSendMsg(data) {
      data.url = `${data.url}/${this.contractId}?processId=${this.processId}`;
      try {
        const { code } = await pressSendMsg(data);
        if (code === 200) {
          // 成功
          this.queryProcessData();
        }
      } catch (error) {
        console.error(error);
      }
    },
    showCommentDialog() {
      this.$refs['commentDialogRef'].dialogVisible = true;
    },
    relatedOrdersShow() {
      this.formatOrderToTable(this.realOrders);
      this.showRelatedOrders = true;
      this.$refs['relatedOrders'].init();
    },
    relatedDrawerHide() {
      this.showRelatedOrders = false;
    },
    // 关联实际订单
    async confirmRelatedOrder(data) {
      try {
        const params = Object.create(null);
        params.id = this.contractId;
        params.orders = this.formatRelatedParams(data);
        await storeRealOrders(params);
        this.showRelatedOrders = false;
        this.init();
      } catch (e) {
        this.showRelatedOrders = false;
      }
    },
    formatRelatedParams(data) {
      if (!(data instanceof Object)) return [];
      const orders = [];
      Object.keys(data).forEach(key => {
        data[key].forEach(item => {
          const curOrder = Object.create(null);
          switch (key) {
            case 'channelTable':
              curOrder.orderType = 1;
              break;
            case 'projectChannelTable':
              curOrder.orderType = 4;
              break;
            case 'projectTable':
              curOrder.orderType = 2;
              break;
          }
          curOrder.relatedId = item.relatedId || item.id;
          orders.push(curOrder);
        });
      });
      return orders;
    },
    // 高级撤回
    handleHigherRecall() {
      showModal('当前审批任务已完成，撤回后最后一步需要重新审批，请谨慎操作').then(() => {
        contractHigherRecall({ id: this.processId }).then(_ => {
          this.$message.success('撤回成功');
          this.init();
        }).catch(_ => {});
      });
    },
    // 重新提交
    handleResubmit() {
      showModal('当前审批未过审，请确认无误后进行重新提交，提交后将重新开始审批，如有内容调整请修改后再提交').then(() => {
        contractResubmit({ id: this.processId }).then(_ => {
          this.$message.success('提交成功');
          this.init();
        }).catch(_ => {});
      });
    },
    // 审批审批转交
    handleApproverChange() {
      this.$refs['approverChangeDialog'].dialogVisible = true;
    },
    // kol合同关联账号同步资源
    handleSyncAccount(id) {
      if (!this.detailData.contractInfo.code && !this.$refs['dynamicDetailRef'].code) {
        this.$message.warning('合同编号未生成，无法同步');
        return;
      }
      showModal('确认关联合同信息吗？').then(() => {
        if (!id) {
          this.$message.warning('无法获取账号ID');
          return;
        }
        const params = {
          id: this.contractId,
          mediumId: id
        };
        contractAccountSync(params).then(res => {
          res.code === 200 && this.$message.success('同步成功');
        });
      });
    },
    toSupplierAudit() {
      const routeUrl = this.$router.resolve({
        name: 'supplierCreate',
        query: {
          legalId: this.detailData.id,
          from: this.detailData.contractInfo.oppCompanyType === 0 ? 'saleSupplier' : 'mengliSupplier'
        }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>

<style lang="scss" scoped>
.pagination-flex {
  // z-index: 2001;
  z-index: 2000; // 页面刷新,底部操作显示层级太高
}
.customer-container {
  min-height: calc(100vh - 56px);
  padding-bottom: 56px;
  position: relative;
  .press-img{
    position: absolute;
    width: 86px;
    height: 75px;
    top: 0;
    left: 16px;
    z-index: 999;
  }
  &::v-deep {
    .el-drawer {
      min-width: 392px;
    }
    .process-operation {
      position: relative;
    }
  }
}
::v-deep .file-item {
  line-height: 32px !important;
}
.process-content-box {
  // padding-top: 12px;
  padding: 4px 5px 0 12px;
  height: calc(100vh - 44px);
  @include scrollBar($x: hidden, $y: auto);
}
.suspend-btn {
  position: fixed;
  right: 16px;
  top: 50%;
  z-index: 2001;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;;
  border-top-left-radius: 8px;
  border-bottom-left-radius: 8px;
  color: #fff;
  cursor: pointer;
  background: linear-gradient(163deg, #93ADFF 0%, #2754E2 100%);
  box-shadow: 0px 3px 7px rgba(39, 84, 226, 0.31);
  .icon {
    font-size: 16px;
    font-weight: 500;
  }
  .text {
    font-size: 12px;
  }
  .suspend-btn-img {
    width: 14px;
    height: 17px;
  }
}
.progress-type-box {
  display: flex;
  margin: 0 12px;
  border-bottom: 1px solid #E6EDFF;
  .progress-type-btn {
    cursor: pointer;
    font-size: 16px;
    color: #333333;
    margin-right: 32px;
    padding-bottom: 5px;
    &.active {
      color: #406EFF;
      font-weight: bold;
      border-bottom: 2px solid #406EFF;
    }
  }
  .progress-type-btn:last-child {
    margin-right: 0px;
  }
}
.progress-type-in-mobile {
  .progress-type-btn {
    font-size: 14px !important;
    margin-right: 12px !important;
  }
  .progress-type-btn:last-child {
    margin-right: 0 !important;
  }
}
.customer-info {
  min-height: calc(100vh - 80px);
  margin: 16px 16px 0;
  background-color: #fff;
  padding-bottom: 60px;
  &.pb-24 {
    padding-bottom: 24px
  }
}
.process-box {
  background: #fafbff;
  border: 1px solid #E6EDFF;
  border-radius: 8px;
  padding: 13px 0px 0px 0px !important;
}

.scroll-box {
  height: calc(100vh - 205px);
  overflow-y: auto;
  overflow-x: hidden;
}
.box-scroll {
  height: calc(100vh - 160px);
  overflow-y: auto;
  overflow-x: hidden;
}
.container-scroll-box {
  min-height: 400px;
  .empty-btn-style {
    border-color: #406EFF;
    background: #fff;
    color: #406EFF;
    width: 80px;
    padding: 7px 0;
    text-align: center;
  }
  .title-btn-right {
    position: absolute;
    right: 0;
  }
}
.btns-container {
  margin-top: 20px;
}
.pd-top0 {
  padding-top: 0;
}
</style>
<style lang="scss">
.message-btn-margin  .el-message-box__btns .el-button--default:first-child {
    margin-right: -220px;
}
</style>
